package com.bing.scanner;

import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.InvocationTargetException;

public class BingFactoryBean<T>  implements FactoryBean<T> {
    private Class<T> bingAnnotationClass;
    private String aliasName;
 public BingFactoryBean(Class<T> bingAnnotationClass) {
        this.bingAnnotationClass = bingAnnotationClass;
    }
    public BingFactoryBean() {

    }

    @Override
    public T getObject() throws Exception {
        //获取类实例,模仿Mybatis中，sqlsession.getMapper(class)方法;
        T t = getInstance(bingAnnotationClass);
        return t;
    }

    private T getInstance(Class<T> bingAnotationClass) {

        try {
            return bingAnotationClass.getDeclaredConstructor().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<T> getObjectType() {
        return this.bingAnnotationClass;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isSingleton() {
        return true;
    }

    public Class<T> getBingAnnotationClass() {
        return bingAnnotationClass;
    }

    public void setBingAnnotationClass(Class<T> bingAnnotationClass) {
        this.bingAnnotationClass = bingAnnotationClass;
    }
    public String getAliasName() {
        return aliasName;
    }

    public void setAliasName(String aliasName) {
        this.aliasName = aliasName;
    }
}
